<!--
  用户新增/编辑弹窗组件
  @author Wu.Liang
  @date 2024-12-21
-->
<template>
    <el-dialog 
        v-model="dialogVisible" 
        :title="dialogTitle" 
        width="700px" 
        :close-on-click-modal="false"
        @close="handleClose"
    >
        <el-form 
            ref="formRef" 
            :model="formData" 
            :rules="formRules" 
            label-width="100px"
            class="user-form"
        >
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="用户名" prop="username">
                        <el-input 
                            v-model="formData.username" 
                            placeholder="请输入用户名"
                            :disabled="mode === 'edit'"
                            clearable
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="真实姓名" prop="realName">
                        <el-input 
                            v-model="formData.realName" 
                            placeholder="请输入真实姓名"
                            clearable
                        />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="手机号" prop="phone">
                        <el-input 
                            v-model="formData.phone" 
                            placeholder="请输入手机号"
                            :disabled="mode === 'edit'"
                            clearable
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="邮箱" prop="email">
                        <el-input 
                            v-model="formData.email" 
                            placeholder="请输入邮箱"
                            clearable
                        />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="昵称" prop="nickname">
                        <el-input 
                            v-model="formData.nickname" 
                            placeholder="请输入昵称"
                            clearable
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="用户类型" prop="userType">
                        <el-select 
                            v-model="formData.userType" 
                            placeholder="请选择用户类型"
                            style="width: 100%"
                        >
                            <el-option label="居民" :value="1" />
                            <el-option label="物业" :value="2" />
                            <el-option label="管理员" :value="3" />
                            <el-option label="其他" :value="4" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20" v-if="mode === 'edit'">
                <el-col :span="12">
                    <el-form-item label="状态" prop="status">
                        <el-radio-group v-model="formData.status">
                            <el-radio :value="1">启用</el-radio>
                            <el-radio :value="0">禁用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20" v-if="mode === 'add'">
                <el-col :span="12">
                    <el-form-item label="密码" prop="password">
                        <el-input 
                            v-model="formData.password" 
                            type="password" 
                            placeholder="请输入密码"
                            show-password
                            clearable
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="确认密码" prop="confirmPassword">
                        <el-input 
                            v-model="formData.confirmPassword" 
                            type="password" 
                            placeholder="请确认密码"
                            show-password
                            clearable
                        />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-form-item label="头像" prop="avatar">
                <ImageUpload
                    v-model="avatarImageList"
                    :upload-type="'USER_AVATAR'"
                    :upload-source="'WEB'"
                    :multiple="false"
                    :max-size="2"
                    :allowed-types="['jpg', 'jpeg', 'png', 'gif']"
                    :limit="1"
                    tip="请上传头像图片，支持jpg、jpeg、png、gif格式，最大2MB"
                    @on-success="handleAvatarSuccess"
                    @on-error="handleAvatarError"
                    @on-change="handleAvatarChange"
                />
            </el-form-item>

            <el-form-item label="备注" prop="remark">
                <el-input 
                    v-model="formData.remark" 
                    type="textarea" 
                    :rows="3"
                    placeholder="请输入备注信息"
                    maxlength="200"
                    show-word-limit
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="loading">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { createUser, updateUser, type UserFormData, getUserDetail } from '@/api/user'
import ImageUpload from '@/components/ImageUpload.vue'
import type { ImageInfo } from '@/components/ImageUpload.vue'
import { createAvatarImageInfo } from '@/utils/avatarUtils'

// Props
interface Props {
    modelValue: boolean
    mode: 'add' | 'edit'
    userData?: any
}

const props = withDefaults(defineProps<Props>(), {
    mode: 'add'
})

// Emits
const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    'success': []
}>()

// 响应式数据
const loading = ref(false)
const formRef = ref<FormInstance>()
const avatarImageList = ref<ImageInfo[]>([])

// 表单数据
const formData = reactive<UserFormData & { confirmPassword?: string; avatar?: string }>({
    username: '',
    password: '',
    confirmPassword: '',
    realName: '',
    nickname: '',
    phone: '',
    email: '',
    userType: 1, // 默认为居民
    status: 0,
    remark: '',
    avatar: undefined
})

// 计算属性
const dialogVisible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
})

const dialogTitle = computed(() => {
    return props.mode === 'add' ? '新增用户' : '编辑用户'
})

// 表单验证规则
const formRules: FormRules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
    ],
    realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '真实姓名长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    email: [
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    userType: [
        { required: true, message: '请选择用户类型', trigger: 'change' }
    ],
    ...(props.mode === 'add' ? {
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
            { required: true, message: '请确认密码', trigger: 'blur' },
            {
                validator: (rule, value, callback) => {
                    if (value !== formData.password) {
                        callback(new Error('两次输入的密码不一致'))
                    } else {
                        callback()
                    }
                },
                trigger: 'blur'
            }
        ]
    } : {})
}

// 监听用户数据变化
watch(() => props.userData, (newData) => {
    if (newData && props.mode === 'edit') {
        Object.assign(formData, {
            id: newData.id,
            username: newData.username,
            realName: newData.realName,
            nickname: newData.nickname,
            phone: newData.phone,
            email: newData.email,
            userType: newData.userType,
            status: newData.status,
            remark: newData.remark,
            avatar: newData.avatar
        })
        
        // 初始化头像图片列表
        if (newData.avatar) {
            const avatarInfo = createAvatarImageInfo(newData.avatar, 'current-avatar')
            if (avatarInfo) {
                avatarImageList.value = [{
                    id: 'current-avatar',
                    url: avatarInfo.fileUrl,
                    fileUrl: avatarInfo.fileUrl,
                    fileName: avatarInfo.fileName
                }]
            } else {
                avatarImageList.value = []
            }
        } else {
            avatarImageList.value = []
        }
        // 延迟清除验证错误，确保数据完全加载后再清除
        nextTick(() => {
            setTimeout(() => {
                formRef.value?.clearValidate()
            }, 100)
        })
    }
}, { immediate: true })

// 监听弹窗显示状态
watch(() => props.modelValue, async (visible) => {
    if (visible) {
        if (props.mode === 'add') {
            resetForm()
        } else if (props.mode === 'edit' && props.userData) {
            try {
                // 先获取完整的用户详情数据
                const response = await getUserDetail(props.userData.id)
                if (response.data) {
                    Object.assign(formData, {
                        id: response.data.id,
                        username: response.data.username,
                        realName: response.data.realName,
                        nickname: response.data.nickname,
                        phone: response.data.phone,
                        email: response.data.email,
                        userType: response.data.userType,
                        status: response.data.status,
                        remark: response.data.remark
                    })
                } else {
                    // 如果获取详情失败，使用传入的数据
                    Object.assign(formData, {
                        id: props.userData.id,
                        username: props.userData.username,
                        realName: props.userData.realName,
                        nickname: props.userData.nickname,
                        phone: props.userData.phone,
                        email: props.userData.email,
                        userType: props.userData.userType,
                        status: props.userData.status,
                        remark: props.userData.remark
                    })
                }
            } catch (error) {
                console.error('获取用户详情失败:', error)
                // 获取详情失败时，使用传入的数据
                Object.assign(formData, {
                    id: props.userData.id,
                    username: props.userData.username,
                    realName: props.userData.realName,
                    nickname: props.userData.nickname,
                    phone: props.userData.phone,
                    email: props.userData.email,
                    userType: props.userData.userType,
                    status: props.userData.status,
                    remark: props.userData.remark
                })
            }
        }
    }
})

// 方法
const resetForm = () => {
    Object.assign(formData, {
        id: undefined,
        username: '',
        password: '',
        confirmPassword: '',
        realName: '',
        nickname: '',
        phone: '',
        email: '',
        userType: 1, // 默认为居民
        status: 0,
        remark: '',
        avatar: undefined
    })
    avatarImageList.value = []
    formRef.value?.clearValidate()
}

// 头像相关方法
const getAvatarInitial = () => {
    const name = formData.realName || formData.username || 'U'
    return name.charAt(0).toUpperCase()
}

const getAvatarImageInfo = () => {
    // 使用工具函数创建头像图片信息
    return createAvatarImageInfo(formData.avatar, 'user-avatar')
}

const handleAvatarSuccess = (response: any, file: any, fileList: ImageInfo[]) => {
    if (response && response.data) {
        formData.avatar = response.data.fileUrl || response.data.url
        ElMessage.success('头像上传成功')
    } else {
        ElMessage.error('头像上传失败：' + (response.message || '未知错误'))
    }
}

const handleAvatarError = (error: any, file: any, fileList: ImageInfo[]) => {
    ElMessage.error('头像上传失败：' + (error.message || '未知错误'))
}

const handleAvatarChange = (file: any, fileList: ImageInfo[]) => {
    if (fileList.length > 0) {
        const latestImage = fileList[fileList.length - 1]
        formData.avatar = latestImage.fileUrl || latestImage.url
    } else {
        formData.avatar = undefined
    }
}

const handleClose = () => {
    dialogVisible.value = false
    resetForm()
}

const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        loading.value = true

        const submitData = { ...formData }
        
        // 编辑模式下移除密码相关字段
        if (props.mode === 'edit') {
            delete submitData.password
            delete submitData.confirmPassword
        } else {
            delete submitData.confirmPassword
        }

        if (props.mode === 'add') {
            await createUser(submitData)
            ElMessage.success('新增用户成功')
        } else {
            await updateUser(submitData.id!, submitData)
            ElMessage.success('更新用户成功')
        }

        emit('success')
        handleClose()
    } catch (error: any) {
        if (error !== 'cancel') {
            console.error('操作失败:', error)
            // 提供更详细的错误信息
            let errorMessage = '操作失败'
            if (error.response?.data?.message) {
                errorMessage = error.response.data.message
            } else if (error.message) {
                errorMessage = error.message
            } else if (typeof error === 'string') {
                errorMessage = error
            }
            ElMessage.error(errorMessage)
        }
    } finally {
        loading.value = false
    }
}
</script>

<style scoped>
.user-form {
    padding: 20px 0;
}

.dialog-footer {
    text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .user-form {
        padding: 10px 0;
    }
}
</style> 